package com.company.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.bookstore.entities.user_admin_module.User;
import com.company.bookstore.exception.user_admin_module.CustomException;
import com.company.bookstore.mapper.user_admin_module.UserMapper;
import com.company.bookstore.qo.user_admin_module.UserQo;
import com.company.bookstore.service.user_admin_module.UserService;
import com.company.bookstore.validator.user_admin_module.UserQoUpdateRegisterValidator;
import com.company.bookstore.validator.user_admin_module.ValidatorFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 吴经纶
 * @blame Android Team
 * @since 2020-08-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> userQueryWrapper= new QueryWrapper<User>().eq("username",username);
        return getOne(userQueryWrapper);
    }

    @Override
    public boolean save(String username, String password) {
       return save(User.builder().username(username).password(password).enable(1).deleted(0).build());
    }

    @Override
    public boolean updateUserQo(UserQo userQo) throws NoSuchMethodException, CustomException {
        if (ValidatorFactory.Invoke(UserQoUpdateRegisterValidator.class.getName(),userQo)){
//            反射字段 并新建 对应 类
            try {
                User user = User.builder().build();
                BeanUtils.copyProperties(userQo,user);
                if (userQo.getPassword()!=null){
                    user.setPassword(bCryptPasswordEncoder.encode(userQo.getPassword()));
                }
                updateById(user);
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }


}
